package com.yanqu.road.dao.impl.union.cross;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.union.cross.CrossUnionNotice;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionNoticeDaoImpl extends TempDataObjectDao<CrossUnionNotice> {

	public Map<String, LinkedList<CrossUnionNotice>> getUnionNoticeMap(long selectTime, int maxCount) {
		ResultSet rs = null;
		CallableStatement call = null;
		Map<String, LinkedList<CrossUnionNotice>> dataMap = new ConcurrentHashMap<>();
		String sql = "select * from t_c_union_notice where noticeTime>? order by noticeTime desc";
		try {
			getDb().setConnName(DbNameStrategy.getCross2Db());
			call = getDb().getConnection().prepareCall(sql);
			call.setLong(1, selectTime);
			rs = call.executeQuery();
			while (rs.next()) {
				CrossUnionNotice data = parse(rs);
				if(!dataMap.containsKey(data.getUnionUid())){
					dataMap.put(data.getUnionUid(), new LinkedList<>());
				}
				LinkedList<CrossUnionNotice> dataList = dataMap.get(data.getUnionUid());
				if(dataList.size() < maxCount) {
					dataMap.get(data.getUnionUid()).addFirst(data);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return dataMap;
	}

	@Override
	protected boolean addData(CrossUnionNotice data) {
		PreparedStatement call = null;
		String sql = "INSERT INTO t_c_union_notice(unionUid,type,userId,nickName,noticeTime,content) VALUES (?,?,?,?,?,?)";
		try {
			getDb().setConnName(DbNameStrategy.getCross2Db());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setString(i++, data.getUnionUid());
			call.setInt(i++, data.getType());
			call.setLong(i++, data.getUserId());
			call.setString(i++, data.getNickName());
			call.setLong(i++, data.getNoticeTime());
			call.setString(i++, data.getContent());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected boolean updateData(CrossUnionNotice data) {
		return false;
	}

	@Override
	protected CrossUnionNotice parseData(ResultSet rs) throws SQLException {
		CrossUnionNotice data = new CrossUnionNotice();
		data.setUnionUid(rs.getString("unionUid"));
		data.setType(rs.getInt("type"));
		data.setUserId(rs.getLong("userId"));
		data.setNickName(rs.getString("nickName"));
		data.setNoticeTime(rs.getLong("noticeTime"));
		data.setContent(rs.getString("content"));
		return data;
	}
}
